package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.message.*;

import java.rmi.RemoteException;
import java.util.*;

/**
 * MessageSendHelper.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.10 $ $Date: 2005/02/08 21:39:22 $
 */
public class MessageSendHelper {
	// TODO rozsirit, vybrat viac veci z commandu a tak
	private AbstractCommand command;

	public MessageSendHelper(AbstractCommand command) {
		this.command = command;
	}

	/**
	 * Sending message for user using his property as a context.
	 *
	 * @param u recipient and command invoker in one
	 * @param key message key
	 * @throws java.rmi.RemoteException
	 */
	public void sendMessage(User u, String key) throws RemoteException {
		u.send(getMessageFactory().getString(key, u.getProperties()));
	}

	/**
	 * Sends message to all users in the same location user is in.
	 *
	 * @param user
	 * @param userKey if null nothing is sent to user
	 * @param audienceKey if null nothing is set to audience
	 * @param category
	 * @throws RemoteException
	 */
	public void sendLocal(User user, String userKey, String audienceKey, Category category) throws RemoteException {
		Location loc = new LocationHelper(command.commandDispatcher).locationForUser(user);
		sendLocal(user, loc, userKey, audienceKey, category);
	}

	public void sendLocal(User user, Location loc, String userKey, String audienceKey, Category category) throws RemoteException {
		if (loc != null) {
			sendMass(user, userKey, loc.users(), audienceKey, category);
		} else {
			if (userKey != null) {
				sendMessage(user, userKey);
			}
		}
	}

	public void sendGlobal(User user, String userKey, String audienceKey, Category category) throws RemoteException {
		sendMass(user, userKey, command.commandDispatcher.getUserFinder().onlineUsers(), audienceKey, category);
	}

	private void sendMass(User user, String userKey, Collection<User> audience, String audienceKey, Category category) throws RemoteException {
		if (userKey != null) {
			sendMessage(user, userKey);
		}
		if (audienceKey != null) {
			Set excluded = new HashSet();
			excluded.add(user);
			command.sendMassMessage(
				command.messageFactory().createMessage(audienceKey, user.getProperties()),
				audience,
				excluded,
				category
			);
		}
	}

	private MessageFactory getMessageFactory() {
		return command.commandDispatcher.getMessageFactory();
	}
}
